<template>
  <div>
    <a-card style="min-height: 70vh">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item ref="name" label="任务名称" prop="name">
          <a-input
            placeholder="请输入任务名称"
            :maxLength="20"
            v-model="form.name"
            @blur="
              () => {
                $refs.name.onFieldBlur()
              }
            "
          />
        </a-form-model-item>
        <a-form-model-item ref="name" label="执行时间" prop="startDate">
          <a-range-picker :placeholder="['开始时间', '结束时间']" format="YYYY-MM-DD HH:mm:ss" :value="[form.startDate, form.endDate]" @change="timeChange" show-time type="date" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item ref="name" label="投放时间" prop="publishDate">
          <a-date-picker format="YYYY-MM-DD HH:mm:ss" show-time v-model="form.publishDate" @change="handChange" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item label="推广说明" prop="description">
          <a-input v-model="form.description" type="textarea" style="height: 60px" :maxLength="120" />
        </a-form-model-item>
        <a-form-model-item label="投放品牌" required>
          <template v-for="tag in regionList">
            <a-checkable-tag :key="tag.key" :checked="brandId.indexOf(tag.key) > -1" @change="checked => handleChange(tag.key, checked)">
              {{ tag.value }}
            </a-checkable-tag>
          </template>
        </a-form-model-item>

        <a-form-model-item label="选择区域" prop="areasId">
          <a-tree-select
            v-model="form.areasId"
            style="width: 70%"
            :dropdownStyle="{ maxHeight: '476px' }"
            :tree-data="treeData"
            tree-checkable
            allowClear
            placeholder="请选择区域"
            search-placeholder="Please select"
            @change="onChange"
          />
        </a-form-model-item>
        <a-form-model-item label="任务素材" required>
          <div v-if="material" class="material-box">
            <div class="img-box">
              <a-icon @click="deleteMaterial" type="close-circle" theme="filled" style="position: absolute; top: -12px; right: -34px; font-size: 24px" />
              <img :src="material.backgroundImage" alt="" />
            </div>
            <div class="desc-box">
              <p>{{ material.name }}</p>
              <p>ID: {{ material.lookId }}</p>
            </div>
          </div>
          <a-button @click="select" type="primary">选择素材</a-button>
        </a-form-model-item>
      </a-form-model>

      <a-form-model-item :wrapper-col="{ span: 24, offset: 16 }" style="margin-top: 24px">
        <a-button @click="handleBack">取消</a-button>
        <a-button style="margin-left: 8px" @click="preservation" type="primary">确定</a-button>
      </a-form-model-item>
    </a-card>
    <selectMaterial ref="selectMaterial" @selectdMaterial="getMaterial" :material="material.lookId"></selectMaterial>
  </div>
</template>
<script>
import { storeList, taskEdit, taskInfo } from '@/api/pos/extension'
import { TreeSelect } from 'ant-design-vue'
const SHOW_ALL = TreeSelect.SHOW_ALL
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import { component } from 'vuedraggable'
import selectMaterial from './components/selectMateria.vue'
// import { themeList } from '@/api/pos/match'
import { guideDetail } from '@/api/pos/match'
export default {
  components: {
    selectMaterial
  },
  data() {
    return {
      SHOW_ALL,
      form: {
        name: '',
        startDate: null,
        endDate: null,
        description: '',
        publishDate: '',
        areasId: []
      },
      id: this.$route.params.id,
      userInfo: Vue.ls.get(USER_INFO),
      manufacturerList: [],
      distributionList: [],
      treeData: [],
      brandId: [],
      regionList: [
        {
          value: 'JNBY',
          key: '2738574294'
        },
        {
          value: '速写CROQUIS',
          key: '2504948039'
        },
        {
          value: 'Pomme de terre',
          key: '6924108367'
        },
        {
          value: 'LESS',
          key: '2822095692'
        },
        {
          value: 'jnby by JNBY',
          key: '4'
        },
        {
          value: 'JNBYHOME',
          key: '8348044436'
        },
        {
          value: '江南布衣+',
          key: '5'
        },

        {
          value: '江南布衣官方Outlet',
          key: '11'
        },

        {
          value: 'APN73',
          key: '15'
        }
      ],
      paramId: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      departType: '',
      rules: {
        name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入推广说明', trigger: 'blur' }],
        startDate: [{ required: true, message: '请选择执行时间', trigger: 'change' }],
        publishDate: [{ required: true, message: '请选择投放时间', trigger: 'change' }],
        areasId: [{ required: true, message: '请选择区域', trigger: 'change' }]
      },
      material: '' // 选择的素材
    }
  },
  mounted() {
    this.manufacturer()
    this.distribution()
  },
  created() {
    if (this.id && this.id != 'add') {
      this.postDetail()
    }
  },
  methods: {
    loadData() {
      let Z = new Promise((resolve, reject) => {
        let data = { departType: 'Z' }
        storeList(data).then(res => {
          if (res.code === 200) {
            this.manufacturerList = res.data
            resolve()
          } else {
            reject(err)
          }
        })
      })
      let J = new Promise((resolve, reject) => {
        let data = { departType: 'J' }
        storeList(data).then(res => {
          if (res.code === 200) {
            this.distributionList = res.data
            resolve()
          } else {
            reject(err)
          }
        })
      })
      Promise.all([Z, J])
        .then(() => {
          this.formatStore()
        })
        .catch(err => {
          callback(err)
        })
    },

    onChange(value, label, extra) {
      let paramId = []
      value.map(item => {
        this.treeData.map(value => {
          if (value.children && value.children.length) {
            value.children.map(_item => {
              if (item == _item.value) {
                paramId.push(_item.id)
              }
              return _item
            })
          }
          return value
        })
        return item
      })
      let info = value
      var parent = this.treeData
        .filter(v => {
          return v.children.some(c => info.includes(c.value))
        })
        .map(v => v.value)
        .join(',')

      this.departType = parent == '1156' ? 'Z' : parent == '1256' ? 'J' : 'Z,J'
      this.paramId = paramId
      console.log(this.departType, ' this.departType')
      console.log(paramId, 'paramId')
    },
    select() {
      this.$refs.selectMaterial.show()
    },
    getMaterial(val) {
      this.material = val
    },
    deleteMaterial() {
      this.material = ''
    },
    handleChange(tag, checked) {
      const { brandId } = this
      const nextSelectedTags = checked ? [...brandId, tag] : brandId.filter(t => t !== tag)
      this.brandId = nextSelectedTags
    },
    handChange(date, dateString) {
      this.form.publishDate = dateString
    },
    timeChange(dates, dateString) {
      this.form.startDate = dateString[0]
      this.form.endDate = dateString[1]
    },
    handleBack() {
      this.$router.back()
    },
    preservation() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (!this.brandId.length) {
            this.$message.error('请选择投放品牌！')
            return
          }
          if (!this.material.lookId) {
            this.$message.error('请选择任务素材！')
            return
          }
          let params = JSON.parse(JSON.stringify(this.form))
          params.areasId = this.paramId.toString()
          params.brandIds = this.brandId.toString()
          params.departType = this.departType
          params.lookId = this.material.lookId
          params.themeId = this.material.themeId
          params.workNo = this.userInfo.workNo // 审核人工号
          params.type = '1'
          if (this.id && this.id != 'add') {
            params.id = this.id
          }
          taskEdit(params).then(res => {
            if (res.code === 200) {
              this.$message.success('成功')
              this.$router.push(`/pos+/match/extension/list`)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取 直营区域
    manufacturer() {
      let data = { departType: 'Z' }
      storeList(data).then(res => {
        if (res.code === 200) {
          this.manufacturerList = res.data
          this.formatStore()
        }
      })
    },
    // 获取经销区域
    distribution() {
      let data = { departType: 'J' }
      storeList(data).then(res => {
        if (res.code === 200) {
          this.distributionList = res.data
          this.formatStore()
        }
      })
    },
    // 回显
    postDetail() {
      let data = {
        taskId: this.id
      }
      taskInfo(data).then(res => {
        if (res.code == 200) {
          console.log(res.data)
          let params = JSON.parse(JSON.stringify(res.data))
          // params.areasId = res.data.areasId.split(',')
          this.brandId = res.data.brandIds ? res.data.brandIds.split(',') : ''
          this.form = params
          this.param(params.areasId.split(','), params.departType)
          this.theme(params.themeId)
          this.departType = params.departType
        }
      })
    },
    param(areasId, departType) {
      let parent = departType == 'Z' ? '1156' : departType == 'J' ? '1256' : ''
      // parent='1156' 直营，parent=1256 经销，parent='' 全选
      // let paramList = []
      let paramList = new Set()
      areasId.map(item => {
        this.treeData.map(value => {
          if (value.children && value.children.length) {
            value.children.map(_item => {
              let key = _item.key
              if (item == _item.id && (parent == '' || _item.key == item + parent)) {
                // paramList.push(_item.value)
                paramList.add(_item.value)
              }
              return _item
            })
          }
          return value
        })
        return item
      })
      console.log(paramList, 'paramList')
      this.form.areasId = Array.from(paramList)
    },
    theme(themeId) {
      let data = {
        themeId: themeId
      }
      guideDetail(data).then(res => {
        if (res.code === 200) {
          this.material = res.data ? res.data : ''
        }
      })
    },

    // 格式化 区域
    formatStore() {
      let manufacturerList = this.manufacturerList.map(item => {
        let storeItem = {
          title: item.name,
          value: item.id + '1156',
          key: item.id + '1156',
          id: item.id
        }
        return storeItem
      })
      let distributionList = this.distributionList.map(item => {
        let storeItem = {
          title: item.name,
          value: item.id + '1256',
          key: item.id + '1256',
          id: item.id
        }
        return storeItem
      })
      let treeData = [
        {
          title: '直营',
          value: '1156',
          key: '1156',
          children: manufacturerList
        },
        {
          title: '经销',
          value: '1256',
          key: '1256',
          children: distributionList
        }
      ]
      console.log(treeData, 'treeData')
      this.treeData = treeData
    }
  }
}
</script>
<style scoped lang="less">
.footer-box {
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
  position: relative;
  background-color: #fff;
  height: 60px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
/deep/ .ant-tag-checkable {
  border: 1px solid #ccc;
}

.material-box {
  display: inline-block;
  width: 160px;
  height: 260px;
}
.img-box {
  width: 160px;
  height: 220px;
  display: flex;
  align-items: center;
  position: relative;
}
.img-box > img {
  width: 160px;
  max-height: 220px;
}
.desc-box {
  height: 40px;
  line-height: 18px;
}
</style>
